<template>
  <div class="webview__login--container">
    <header data-tauri-drag-region class="titlebar">
      <updater />
      <div class="close_icon" @click="handleClose">
        <n-icon :size="18" color="#fff">
          <Close />
        </n-icon>
      </div>
    </header>
    <section class="webview__main--container">
      <div v-if="loading" class="skeleton_wrap">
        <header class="avatar__wrap">
          <n-skeleton circle height="75px" width="75px" />
        </header>
        <main class="input__content">
          <n-skeleton width="70%" height="38px" :sharp="false" size="medium" />
          <n-skeleton width="70%" height="38px" :sharp="false" size="medium" />
          <div class="remeber__pwd">
            <n-skeleton :width="16" :height="16" />
            <n-skeleton width="4em" height="16px" :sharp="false" size="medium" />
          </div>
          <n-skeleton width="70%" height="42px" :sharp="false" size="medium" />
          <n-skeleton width="40%" height="16px" :sharp="false" size="medium" />
        </main>
      </div>
      <div v-else class="login_wrap">
        <div class="avatar__wrap">
          <img class="animate__animated animate__bounce" v-if="hasLogin" :src="avatar || undefined"
            :onerror="imgOnError" />
          <img class="animate__animated animate__bounce" v-else :src="defaultImg" style="margin-bottom: 1em;">
          <p v-if="hasLogin" class="name-text">{{ chineseName }}</p>
        </div>
        <main class="input__content">
          <p class="change__account" v-if="hasLogin" @click="loginMode = '2'">切换账号</p>
          <template v-else>
            <input id="userName" class="ipt__wrap" v-model="model.userName" placeholder="请输入账号"  @focus="clearValidate('userName')"/>
            <input id="password" class="ipt__wrap" v-model="model.password" placeholder="请输入密码" type="password" @focus="clearValidate('password')" />
            <div class="remeber__pwd">
              <input type="checkbox" v-model="isRemindPass">
              <label @click="isRemindPass = !isRemindPass">记住密码</label>
            </div>
          </template>
          <button class="login__btn" @click="handeLogin" :disabled="loadingLoading">
            <span>{{ hasLogin ? '一键登录' : '登 录' }}</span>
            <span v-show="loadingLoading" style="margin-left:1rem"> <n-spin stroke="#fff" :size="12" /></span>
          </button>
        </main>
        <footer class="login__footer">
          v{{ appStore.version }}
        </footer>
      </div>
    </section>
  </div>
</template>

<script setup lang='ts'>
import updater from '@/components/updater.vue';
import { Close } from '@vicons/ionicons5';
import { loginApi, getUserInfo } from '@/api/modules/login';
import { setToken } from '@/api/auth';
import { useUserStore } from '@/stores/user';
import { useMessage } from 'naive-ui';
import { Store } from '@tauri-apps/plugin-store';
import { useAppStore } from '@/stores/app';
import { invoke } from '@tauri-apps/api/core';
import { controlWindow } from '@/utils/windows';
import defaultImg from '@/assets/images/avatar.png';
import { storeToRefs } from 'pinia';

const userStore = useUserStore();
const appStore = useAppStore();
const router = useRouter();
const message = useMessage();
const { avatar, chineseName } = storeToRefs(userStore);
const model = reactive({
  userName: '',
  password: '',
});
const loading = ref(true);
const loadingLoading = ref(false);
const isRemindPass = ref(false); //是否记住密码
const loginMode = ref<'1' | '2'>('2'); //1.一键登录 2.账号密码登录
const hasLogin = computed(() => {
  return loginMode.value === '1';
})


const getVersionInfo = async () => {
  try {
    const version = await invoke('get_app_version') as string;
    appStore.setVersion(version);
  } catch (error) {
    appStore.setVersion('unknown');
  }
}
// 初始化项目
const initProject = async () => {
  try {
    await getVersionInfo();
    const userInfo: UserInfo = await getUserInfo() as UserInfo;
    loginMode.value = '1';
    loading.value = false;
    userStore.setUserInfos(userInfo);
    userStore.generateMenu(router);
  } catch (error) {
    loginMode.value = '2';
    initNoTokenProject();
  }
}
initProject();

// 没有token初始化项目
const initNoTokenProject = async () => {
  try {
    const store = await Store.load('.store.bin');
    model.userName = await store.get('userName') || '';
    model.password = await store.get('password') || '';
    isRemindPass.value = await store.get('isRemindPass') || false;
  } catch (error) {
    console.log(error instanceof Error ? error.message : 'store错误');
  } finally {
    loading.value = false;
  }
}

// 登录处理
const handeLogin = async () => {
  if (hasLogin.value) {
    invoke("audio", { filename: "remind.wav" });
    await controlWindow('main', 'resize', { width: 1080, height: 635 });
    router.push('/home');
  } else {
    if (!model.userName && !model.password) {
      const userNameIpt = document.getElementById('userName');
      userNameIpt && userNameIpt.classList.add('error-style');
      const passwordIpt = document.getElementById('password');
      passwordIpt && passwordIpt.classList.add('error-style');
      return message.error('请输入账号和密码！');
    };
    if (!model.userName) {
      const userNameIpt = document.getElementById('userName');
      userNameIpt && userNameIpt.classList.add('error-style');
      return message.error('请输入账号！');
    };
    if (!model.password) {
      const passwordIpt = document.getElementById('password');
      passwordIpt && passwordIpt.classList.add('error-style');
      return message.error('请输入密码！');
    };
    loginRequest();
  }
}
// 账号密码登录
async function loginRequest() {
  try {
    if (loadingLoading.value) return;
    loadingLoading.value = true;
    const res: any = await loginApi(model);
    setToken(res);
    const userInfo: UserInfo = await getUserInfo() as UserInfo;
    if (isRemindPass.value) {
      const store = await Store.load('.store.bin');
      await store.set('userName', model.userName);
      await store.set('password', model.password);
      await store.set('isRemindPass', isRemindPass.value);
    }
    userStore.setUserInfos(userInfo);
    await userStore.generateMenu(router);
    message.success('登录成功！');
    invoke("audio", { filename: "remind.wav" });
    await controlWindow('main', 'resize', { width: 1080, height: 635 });
    router.push('/home');
  } catch (error) {
    message.error(error instanceof Error ? error.message : String(error));
  } finally {
    loadingLoading.value = false;
  }
}

// 图片默认值
const imgOnError = (e: Event) => {
  let img = e.srcElement as HTMLImageElement;
  img.src = defaultImg;
  img.onerror = null; //防止闪图
}

const handleClose = async () => {
  try {
    await controlWindow('main', 'close');
  } catch (error) {
    message.error(error instanceof Error ? error.message : '未知错误，关闭失败！');
  }

}

// 取消校验
const clearValidate = (id:string)=>{
  const documentIpt = document.getElementById(id);
  documentIpt && documentIpt.classList.remove('error-style');
}
</script>
<style scoped lang="scss">
@use "sass:color";
$title-height: 25px;
$input-item-gap: 16px;
$text-color: #5993e9;
$b-radius: 8px;
$btn-color: #0099ff;

.webview__login--container {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: linear-gradient(to bottom, #311b2c, #1f1942, #2c1932);

  // 标题导航区域
  .titlebar {
    height: $title-height;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    cursor: pointer;

    .close_icon {
      width: $title-height;
      height: $title-height;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      &:hover {
        background: #f40;
      }
    }
  }

  // 主体登录区域
  .webview__main--container {

    // 骨架屏
    .skeleton_wrap {
      .avatar__wrap {
        width: 100%;
        display: flex;
        justify-content: center;
        margin: 12% 0 8%;
      }

      .input__content {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: $input-item-gap;

        .remeber__pwd {
          width: 70%;
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          gap: calc($input-item-gap / 2);
        }
      }
    }

    .login_wrap {
      .avatar__wrap {
        width: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        margin: 12% 0 2%;

        img {
          width: 75px;
          height: 75px;
          border-radius: 50%;
          border: 2px solid #fff;
        }

        .name-text {
          font-size: 1.2rem;
          color: #fff;
          line-height: 0.2em;
        }
      }

      // 主体表单
      .input__content {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: $input-item-gap;
        input[type="password"]::-ms-reveal,
        input[type="password"]::-webkit-password-reveal-button {
          filter: brightness(0) invert(1);
        }

        .change__account {
          color: $text-color;
          cursor: pointer;
          height: 50px;
        }

        .login__btn {
          width: 70%;
          height: 38px;
          border-radius: $b-radius;
          outline: none;
          border: none;
          font-size: 0.85rem;
          color: #fff;
          font-weight: 600;
          background: $btn-color;
          cursor: pointer;

          &:hover {
            background-color: color.adjust($btn-color, $lightness: 15%);
          }
        }

        //  记住密码
        .remeber__pwd {
          width: 70%;
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          gap: calc($input-item-gap / 2);

          input[type="checkbox"] {
            /* 隐藏原生复选框 */
            appearance: none;
            -webkit-appearance: none;
            width: 15px;
            height: 15px;
            border: 1px solid #ccc;
            background: #fff;
            border-radius: 4px;
            outline: none;
            cursor: pointer;
            position: relative;

            &:checked {
              background-color: $text-color;
              border-color: #fff;

              &::after {
                content: "✓";
                color: white;
                position: absolute;
                left: 50%;
                top: 50%;
                font-size: 0.7em;
                transform: translate(-50%, -50%);
              }
            }
          }

          label {
            color: #fff;
            cursor: pointer;
            &:hover{
              color:$text-color;
            }
          }
        }

        // 输入框样式
        .ipt__wrap {
          transition: 0.47s all;
          width: calc(70% - 4em);
          border: 1px solid transparent;
          outline: none;
          padding: 0 2em;
          height: 38px;
          border-radius: $b-radius;
          background: #38335780;
          -webkit-backdrop-filter: blur(10px);
          backdrop-filter: blur(10px);
          color: #fff;
          &.error-style{
            border:1px solid #ff440060;
          }
        }
      }

      // 底部
      .login__footer {
        text-align: center;
        margin: 1em 0;
        color: $text-color
      }
    }
  }
}
</style>